package com.huslee.shark.log.log4j2.serialize;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.huslee.shark.log.log4j2.core.LogManager;
import com.huslee.shark.log.log4j2.interfaces.Logger;

/**
 * @author: zhanglin574@xdf.cn
 * @date: 2021/8/11
 * @description:
 */
public class JackSon {
    public static final Logger log = LogManager.getLogger(JackSon.class);

    public static String toJSONString(Object obj){
        try {
            return getMapper().writerWithDefaultPrettyPrinter().writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            log.error("jackson序列化发生异常",e);
        }
        return null;
    }

    public static  <T> T parse(String str, Class<T> tClass){
        try {
            return getMapper().readValue(str, tClass);
        } catch (JsonProcessingException e) {
            log.error("jackson反序列化发生异常",e);
        }
        return null;
    }

    private static ObjectMapper getMapper(){
      return JackSon.Inner.getObjectMapper();
    }

    private static ObjectMapper newInstance(){
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false);
        objectMapper.setSerializationInclusion(JsonInclude.Include.ALWAYS);
        return objectMapper;
    }
  static class Inner{
      private static final ObjectMapper objectMapper = newInstance();

      static ObjectMapper getObjectMapper(){
          return objectMapper;
      }
  }
}
